package com.zxl.live.tools.tools;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

import com.zxl.live.tools.common.ApplicationHelper;

import java.lang.reflect.Method;

/**
 * 和绘制相关的信息接口
 * Created by makai on 15-6-8.
 */
public class DrawUtils {

	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static int getScreenHeight(Context context) {
		Resources resources = context.getResources();
		DisplayMetrics dm = resources.getDisplayMetrics();
		return dm.heightPixels;
	}

	public static int getScreenWidth(Context context) {
		Resources resources = context.getResources();
		DisplayMetrics dm = resources.getDisplayMetrics();
		return dm.widthPixels;
	}

	public static int getTextWidth(Paint paint, String str) {
		int iRet = 0;
		if (str != null && str.length() > 0) {
			int len = str.length();
			float[] widths = new float[len];
			paint.getTextWidths(str, widths);
			for (int j = 0; j < len; j++) {
				iRet += (int) Math.ceil(widths[j]);
			}
		}
		return iRet;
	}

	public static int dip2px(int i) {
		return dip2px(ApplicationHelper.getContext(), i);
	}

	public static int sp2px(int i) {
		return px2dip(ApplicationHelper.getContext(), i);
	}

	public static int dip2pxForXH(float dipValue) {
		return (int) (dipValue / 2 * ApplicationHelper.getContext().getResources().getDisplayMetrics().density + 0.5f);
	}

	public static int getScreenHeight() {
		return getScreenHeight(ApplicationHelper.getContext());
	}

	public static int getScreenWidth() {
		return getScreenWidth(ApplicationHelper.getContext());
	}

	private static int sReadHeight;
	private static int sNavBarHeight =  -1;

	public static void initRealSize(Context context) {
		if (context != null) {
			WindowManager wm = (WindowManager) context
					.getSystemService(Context.WINDOW_SERVICE);
			Display display = wm.getDefaultDisplay();
			try {
				Class<?> disPlayClass = Class.forName("android.view.Display");
				Point realSize = new Point();
				Method method = disPlayClass.getMethod("getRealSize", Point.class);
				method.invoke(display, realSize);
				sReadHeight = realSize.y;
			} catch (Exception e) {
				sReadHeight = getScreenHeight(context);
			}
			sNavBarHeight = sReadHeight - getScreenHeight(context);
		}
	}

	public static int getNavBarHeight(Context context) {
		if (sNavBarHeight < 0) {
			initRealSize(context);
		}
		return sNavBarHeight;
	}
}
